package com.zmn.oms.task.job.third.tmall;

import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.spring.tasktracker.JobRunnerItem;
import com.github.ltsopensource.spring.tasktracker.LTS;
import com.github.ltsopensource.tasktracker.Result;
import com.zmn.common.dto.ResultDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.manager.lts.interfaces.task.TaskManager;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.manager.utils.TaskConsts;
import com.zmn.oms.third.tmall.TmallConsts;
import com.zmn.oms.third.tmall.service.TmallService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

/**
 * 天猫勤鸽渠道查询订单任务实现类
 *
 * @author xiewenbing
 * @date 2021/07/13
 */
@LTS
@Slf4j
public class QueryOrderJob {

    @Autowired
    private TmallService tmallService;

    @Resource
    private TaskManager taskManager;

    /**
     * 每隔30分钟，定时查询天猫勤鸽自营渠道查询失败或创建失败的工单的信息
     */
    @PostConstruct
    void init() {
        Job job = new Job();
        job.setTaskId(TaskConsts.TASK_ID_TMALL_BATCH_QUERY_ORDER_JOB);
        job.setParam(TaskManager.SHARD_FIELD, TaskConsts.TASK_ID_TMALL_BATCH_QUERY_ORDER_JOB);
        job.setCronExpression("0 /30 * * * ?");
        job.setReplaceOnExist(true);
        ResultDTO result = taskManager.submitTask(job);
        if (!result.getStatusBool()) {
            log.error("#oms#tmall#BatchQueryOrderJob# job submit fail...");
        }
    }

    /**
     * 重新查询天猫勤鸽自营渠道查询失败或创建失败的工单的信息
     * @param job
     * @return
     */
    @JobRunnerItem(shardValue = TaskConsts.TASK_ID_TMALL_BATCH_QUERY_ORDER_JOB)
    public Result runBatchQueryOrderJob(Job job) {
        if (!TmallConsts.POWER_ON) {
            log.info("【{}】<订单查询> 该功能没有开启。", TmallConsts.CHANNEL_NAME);
            return null;
        }

        try {
            tmallService.queryOrderByTime();
        } catch (OmsBaseException e) {

            log.info("#oms#tmall#BatchQueryOrderJob# 定时查询天猫勤鸽渠道工单任务执行失败 ！", e.getMessage());
            return new Result(Action.EXECUTE_FAILED,"执行失败");
        }

        log.info("#oms#tmall#BatchQueryOrderJob# 定时查询天猫勤鸽渠道工单任务执行成功 ！");
        return new Result(Action.EXECUTE_SUCCESS, "执行成功了!");
    }
}
